package com.xmlt.ui.editors.browsereditor;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.Action;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.w3c.dom.Node;

import com.xmlt.core.template.Template;
import com.xmlt.core.template.TemplateException;
import com.xmlt.ui.builder.BuilderPlugin;

public class GenerateInstanceAction extends Action {
	private IEditorPart activeEditor;
	public GenerateInstanceAction() {
		setText("Generate new instance");
		setToolTipText("");
	}
	
	public void setActiveEditor(IEditorPart editor) {
		activeEditor = editor;
	}

	@Override
	public void run() {
		IEditorInput input = activeEditor.getEditorInput();
		if (!(input instanceof IFileEditorInput))
			return;
		
		IFile file = ((IFileEditorInput) input).getFile();
		String ref = file.getProjectRelativePath().toString();
		Template t = null;
		try {
			t = BuilderPlugin.getTemplateManager(file.getProject()).findTemplate(ref);
		} catch (TemplateException e1) {
			// TODO: add error reporting
		}
		if (t == null)
			return;
		
		IContainer container = file.getParent();
		String fileName = file.getName();
		String instanceName = fileName.substring(0, fileName.indexOf(".tmpl")) + "_instance";
		int suffix = 1;
		while(container.exists(new Path(instanceName + suffix + ".inst")))
			suffix++;
		
		String instanceFileName = instanceName + suffix + ".inst";
		IFile instanceFile = container.getFile(new Path(instanceFileName));
		if (instanceFile.exists()) {
			// TODO: show error
		} else {
			try {
				String docString = nodeToString(t.generateInstance().getDocument());
				instanceFile.create(new ByteArrayInputStream(docString.getBytes()), true, null);
			} catch (Exception e) {
				// TODO: show error
			}
		}
	}
	
	public String nodeToString(Node n) {
		try {
			Transformer xformer = TransformerFactory.newInstance()
					.newTransformer();
			StringWriter sw = new StringWriter();
			xformer.transform(new DOMSource(n), new StreamResult(sw));
			return sw.toString();
		} catch (TransformerConfigurationException e) {
			//e.printStackTrace();
		} catch (TransformerException e) {
			//e.printStackTrace();
		}
		return "";
	}
}
